package stru1.day10;

import java.util.*;

/**
 * 144. 二叉树的前序遍历
 */
public class Solution1 {
    public static void main(String[] args) {
        System.out.println(preorderTraversal(new TreeNode(1, null, new TreeNode(2, new TreeNode(3), null))));
//        System.out.println(preorderTraversal(null));
        System.out.println(preorderTraversal(new TreeNode(1)));
    }

    /**
     * 利用栈实现
     * 时间复杂度 O(n)
     * 空间复杂度 O(n)
     */
    public static List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> ans = new LinkedList<>();
        if (root == null) return ans;

        Deque<TreeNode> stack = new ArrayDeque<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode curr = stack.pop();
            ans.add(curr.val);
            if (curr.right != null) stack.push(curr.right);
            if (curr.left != null) stack.push(curr.left);
        }

        return ans;
    }

    /**
     * Morris 遍历 （详细见官方题解）
     * 时间复杂度 O(n)
     * 空间复杂度 O(1)
     */
    public static List<Integer> preorderTraversal1(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) {
            return res;
        }

        TreeNode p1 = root, p2;

        while (p1 != null) {
            p2 = p1.left;
            if (p2 != null) {
                while (p2.right != null && p2.right != p1) {
                    p2 = p2.right;
                }
                if (p2.right == null) {
                    res.add(p1.val);
                    p2.right = p1;
                    p1 = p1.left;
                    continue;
                } else {
                    p2.right = null;
                }
            } else {
                res.add(p1.val);
            }
            p1 = p1.right;
        }
        return res;
    }
}
